<template>
  <div class="product-form-page">
    <div class="page-header">
      <h1>{{ isEditMode ? 'Edit Product' : 'Create Product' }}</h1>
      <el-button @click="$router.back()">Back</el-button>
    </div>

    <el-card>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
        v-loading="loading"
      >
        <el-form-item label="Category" prop="category_id">
          <el-select v-model="formData.category_id" placeholder="Select category">
            <el-option
              v-for="cat in categories"
              :key="cat.id"
              :label="cat.name_en"
              :value="cat.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="Name (CN)" prop="name">
          <el-input v-model="formData.name" placeholder="产品名称" />
        </el-form-item>

        <el-form-item label="Name (EN)" prop="name_en">
          <el-input v-model="formData.name_en" placeholder="Product Name" />
        </el-form-item>

        <el-form-item label="Description" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="Product description"
          />
        </el-form-item>

        <el-form-item label="Material" prop="material">
          <el-input v-model="formData.material" placeholder="e.g., Cotton, Lace, Polyester" />
        </el-form-item>

        <el-form-item label="Colors" prop="colors">
          <el-select
            v-model="formData.colors"
            multiple
            filterable
            allow-create
            placeholder="Add colors (e.g., #FF0000)"
          >
            <el-option
              v-for="color in commonColors"
              :key="color.value"
              :label="color.label"
              :value="color.value"
            >
              <div style="display: flex; align-items: center; gap: 0.5rem;">
                <div
                  :style="{
                    width: '20px',
                    height: '20px',
                    backgroundColor: color.value,
                    border: '1px solid #ccc',
                    borderRadius: '4px'
                  }"
                ></div>
                {{ color.label }}
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Sizes" prop="sizes">
          <el-select
            v-model="formData.sizes"
            multiple
            filterable
            allow-create
            placeholder="Add sizes (e.g., S, M, L, XL)"
          >
            <el-option v-for="size in commonSizes" :key="size" :label="size" :value="size" />
          </el-select>
        </el-form-item>

        <el-form-item label="Main Image" prop="main_image" required>
          <el-upload
            :file-list="mainImageList"
            :on-change="handleMainImageChange"
            :before-upload="() => false"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="Gallery Images" prop="images">
          <el-upload
            :file-list="imagesList"
            :on-change="handleImagesChange"
            :on-remove="handleImageRemove"
            :before-upload="() => false"
            multiple
            list-type="picture-card"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="Hot Product" prop="is_hot">
          <el-switch v-model="formData.is_hot" />
        </el-form-item>

        <el-form-item label="Display Order" prop="display_order">
          <el-input-number v-model="formData.display_order" :min="0" />
        </el-form-item>

        <el-form-item label="Status" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">Active</el-radio>
            <el-radio :label="0">Inactive</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEditMode ? 'Update Product' : 'Create Product' }}
          </el-button>
          <el-button @click="$router.back()">Cancel</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { productAPI, categoryAPI } from '@/api'

const route = useRoute()
const router = useRouter()

const isEditMode = computed(() => !!route.params.id)

const loading = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const categories = ref([])

const mainImageList = ref([])
const imagesList = ref([])

const formData = reactive({
  category_id: null,
  name: '',
  name_en: '',
  description: '',
  material: '',
  colors: [],
  sizes: [],
  main_image: null,
  images: [],
  is_hot: false,
  display_order: 0,
  status: 1
})

const commonColors = [
  { label: 'Red', value: '#FF0000' },
  { label: 'Blue', value: '#0000FF' },
  { label: 'Green', value: '#00FF00' },
  { label: 'Yellow', value: '#FFFF00' },
  { label: 'Black', value: '#000000' },
  { label: 'White', value: '#FFFFFF' },
  { label: 'Pink', value: '#FFC0CB' },
  { label: 'Purple', value: '#800080' },
  { label: 'Orange', value: '#FFA500' },
  { label: 'Brown', value: '#A52A2A' }
]

const commonSizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL', '2XL', '3XL', '4XL', '5XL']

const rules = {
  category_id: [{ required: true, message: 'Please select category', trigger: 'change' }],
  name: [{ required: true, message: 'Please enter name (CN)', trigger: 'blur' }],
  name_en: [{ required: true, message: 'Please enter name (EN)', trigger: 'blur' }]
}

const handleMainImageChange = (file) => {
  // Create preview URL for new uploads
  if (file.raw) {
    const url = URL.createObjectURL(file.raw)
    mainImageList.value = [{
      name: file.name,
      url: url,
      raw: file.raw
    }]
    formData.main_image = file.raw
  }
}

const handleImagesChange = (file, fileList) => {
  // Create preview URLs for new uploads
  imagesList.value = fileList.map(f => {
    if (f.raw && !f.url) {
      return {
        name: f.name,
        url: URL.createObjectURL(f.raw),
        raw: f.raw
      }
    }
    return f
  })
  formData.images = fileList.map(f => f.raw).filter(Boolean)
}

const handleImageRemove = (file, fileList) => {
  imagesList.value = fileList
  formData.images = fileList.map(f => f.raw).filter(Boolean)
}

const loadCategories = async () => {
  try {
    const response = await categoryAPI.getAll()
    if (response.success) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('Failed to load categories:', error)
  }
}

const loadProduct = async () => {
  if (!isEditMode.value) return

  try {
    loading.value = true
    const response = await productAPI.getById(route.params.id)
    if (response.success) {
      const product = response.data
      Object.assign(formData, {
        category_id: product.category_id,
        name: product.name,
        name_en: product.name_en,
        description: product.description,
        material: product.material,
        colors: product.colors || [],
        sizes: product.sizes || [],
        is_hot: !!product.is_hot,
        display_order: product.display_order,
        status: product.status
      })

      // Set existing images for preview
      if (product.main_image) {
        mainImageList.value = [{
          name: 'main_image',
          url: product.main_image
        }]
      }

      if (product.images && product.images.length) {
        imagesList.value = product.images.map((url, index) => ({
          name: `image_${index}`,
          url
        }))
      }
    }
  } catch (error) {
    console.error('Failed to load product:', error)
    ElMessage.error('Failed to load product')
  } finally {
    loading.value = false
  }
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (!isEditMode.value && !formData.main_image) {
      ElMessage.error('Please upload main image')
      return
    }

    submitting.value = true

    const formDataToSend = new FormData()
    formDataToSend.append('category_id', formData.category_id)
    formDataToSend.append('name', formData.name)
    formDataToSend.append('name_en', formData.name_en)
    formDataToSend.append('description', formData.description)
    formDataToSend.append('material', formData.material)
    formDataToSend.append('colors', JSON.stringify(formData.colors))
    formDataToSend.append('sizes', JSON.stringify(formData.sizes))
    formDataToSend.append('is_hot', formData.is_hot ? 1 : 0)
    formDataToSend.append('display_order', formData.display_order)
    formDataToSend.append('status', formData.status)

    if (formData.main_image) {
      formDataToSend.append('main_image', formData.main_image)
    }

    formData.images.forEach(image => {
      formDataToSend.append('images', image)
    })

    if (isEditMode.value) {
      await productAPI.update(route.params.id, formDataToSend)
      ElMessage.success('Product updated successfully')
    } else {
      await productAPI.create(formDataToSend)
      ElMessage.success('Product created successfully')
    }

    router.push('/products')
  } catch (error) {
    if (!error.message) {
      return
    }
    console.error('Failed to save product:', error)
    
    // 显示详细错误信息
    if (error.response?.data) {
      console.error('Error details:', error.response.data)
      ElMessage.error(`Failed: ${error.response.data.message || 'Unknown error'}`)
    }
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadCategories()
  loadProduct()
})

// Clean up blob URLs on unmount to prevent memory leaks
onUnmounted(() => {
  mainImageList.value.forEach(file => {
    if (file.url && file.url.startsWith('blob:')) {
      URL.revokeObjectURL(file.url)
    }
  })
  imagesList.value.forEach(file => {
    if (file.url && file.url.startsWith('blob:')) {
      URL.revokeObjectURL(file.url)
    }
  })
})
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;

  h1 {
    margin: 0;
    color: var(--text-primary);
  }
}

:deep(.el-select) {
  width: 100%;
}
</style>

